﻿using System;
using System.Collections;
using System.Collections.Generic;

namespace A77用数组实现一个存整数的MyList类
{
    class MyList<T> where T:IComparable
    {
        private T[] array;
        public MyList()
        {
            array = new T[4];//默认创建长度位4的数组作为容器
        }
        public MyList(int capacity)
        {
            array = new T[capacity];//创建指定长度的数组作为容器
        }
        //元素个数
        public int Count { get;private set; }
        //当前容量
        public int Capacity { get { return array.Length; } }
        //添加元素
        public void Add(T item) 
        {
            //保证容量是够用的
            if (Count==Capacity)//满了
            {
                //创建新数组
                T[] newArray = new T[Capacity<1000? Capacity*2:Capacity+1000];
                //把原来数据拷贝到新数组中
                array.CopyTo(newArray,0);
                //让array指向新数组
                 array=newArray;
            }
            array[Count] = item;
            Count++;
        }
        //从指定位置移除元素
        public void RemoveAt(int index)
        {
            if (index > Count - 1) throw new IndexOutOfRangeException();
            for (int i = index; i < Count-1; i++)
            {
                array[i] = array[i + 1];
            }
            Count--;
        }
        //是否包含某个元素
        public bool Contains(T  item) 
        {
            for (int i = 0; i < Count; i++)
            {
                if (array[i].CompareTo(item)==0)
                {
                    return true;
                }
            }
            return false;
        }

        public T this[int index]
        {
            get
            {
                if (index > Count - 1) throw new IndexOutOfRangeException ();
                return array[index]; 
            }
            set
            {
                if (index > Count - 1) throw new IndexOutOfRangeException();
                array[index] = value;
            }
        }
    }

    
}
